import socket
import json
import hashlib
import getpass


class FtpClient(object):
    def __init__(self, ip, port):
        self.client = socket.socket()
        self.client.connect((ip,port))


    def help(self):
        msg = '''====
ls 
cd ../..
pwd
get filename
put filename
mkdir dirname
exit
===
'''
        print(msg)

    def control(self):
        count = 0
        while count < 3:
            username = input('username: ').strip()
            password = getpass.getpass('password: ').strip()

            # 加密密码
            m = hashlib.md5()
            m.update(password.encode())
            pwd = m.hexdigest()

            user = {
                'name': username,
                'pwd': pwd,
                'form': 'user_auth'
            }
            data_user = json.dumps(user).encode()
            self.client.send(data_user)

            # 收到回复
            recv_data = self.client.recv(1024)
            r1 = json.loads(recv_data.decode())

            self.name = r1['name']
            self.dir = r1['name']

            if r1['status'] == '200':
                print('欢迎: %s' % r1['name'])
                self.__my_interactive()
            else:
                count += 1


    def __my_interactive(self):
        while True:
            cmd = input('%s >> :' % self.dir).strip()
            if len(cmd) == 0:
                continue
            cmd_str = cmd.split()[0]

            if hasattr(self, 'cmd_%s'% cmd_str):
                func = getattr(self, "cmd_%s" % cmd_str)
                func(cmd)
            else:
                self.help()

    def cmd_ls(self, cmd):
        if len(cmd) != 2:
            self.help()

        cmd_str = {
            'dir': self.dir,
            'form': 'cmd_ls'
        }

        data_cmd = json.dumps(cmd_str).encode()

        # 发送信息
        self.client.send(data_cmd)

        # 接受反馈
        recv_data = self.client.recv(1024)
        d1 = json.loads(recv_data.decode())
        print(d1)

    def cmd_cd(self, cmd):
        t1 = cmd.split()
        if len(t1) > 2:
            print('cd 不能接两个路径')
        elif len(t1) == 1:
            self.dir = self.name
        elif t1[1] == '..':
            t2 = self.dir.split('/')
            if len(t2) == 1:
                print('没有上一级了')
            else:
                self.dir = '/'.join(t2[:-1])
        elif t1[1] == '.':
            pass
        else:
            cmd_str = {
                'form': 'cmd_cd',
                'cur_dir': self.dir,
                'go_dir': t1[1]
            }

            data_cmd = json.dumps(cmd_str).encode()

            # 发送给服务端验证目录是否合法
            self.client.send(data_cmd)

            # 接受反馈
            recv_data = self.client.recv(1024)

            d1 = json.loads(recv_data.decode())

            if d1['status'] == '200':
                self.dir += '/'+cmd_str['go_dir']
            else:
                print('没有该目录')

    def cmd_mkdir(self, cmd):
        m1 = cmd.split()
        if len(m1) == 1:
            print('没有指定目录')

        elif len(m1) > 2:
            print('不能指定多个目录')

        else:
            cmd_str = {
                'form': 'cmd_mkdir',
                'cur_dir': self.dir,
                'create_dir': m1[1]
            }

            data_cmd = json.dumps(cmd_str).encode()

            # 发送给服务端
            self.client.send(data_cmd)

            #接受反馈
            recv_data = self.client.recv(1024)
            d1 = json.loads(recv_data.decode())

            if d1['status'] == '403':
                print('无法创建目录-%s：目录已经存在' % cmd_str['create_dir'])
            elif d1['status'] == '404':
                print('无法创建目录-%s：目录不存在' % cmd_str['create_dir'])

    def cmd_pwd(self, cmd):
        print(self.dir)

    def cmd_exit(self, cmd):
        exit(1)

    def cmd_get(self, cmd):
        pass

    def cmd_put(self, cmd):
        pass


u1 = FtpClient('localhost', 9999)
u1.control()



# data = {
#     'xiaoming': {
#         'pwd': '123123',
#         'limit': '20M'
#     },
#
#     'xiaohua': {
#         'pwd': 'abc123',
#         'limit': '30M'
#     },
#
#     'xiaohong': {
#         'pwd': 'abcabc',
#         'limit': '10M'
#     },
#
#     'chenfei': {
#         'pwd': '123456',
#         'limit': '25M'
#     }
# }
#
# with open('../conf/users', 'w') as f:
#     json.dump(data, f)
